import tkinter as tk
import random
import time
from collections import deque
import threading

# 窗口队列，用于存储打开的窗口
window_queue = deque(maxlen=5)


def create_window():
    # 创建主窗口
    root = tk.Tk()
    root.title("Hello World Window")

    # 设置窗口大小
    root.geometry('200x100')

    # 随机设置窗口位置
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    x = random.randint(0, screen_width - 200)
    y = random.randint(0, screen_height - 100)
    root.geometry(f'+{x}+{y}')

    # 创建一个标签，用于显示文本
    label = tk.Label(root, text="Hello World", fg="blue", font=("Arial", 24))
    label.pack(expand=True)

    # 将窗口添加到队列中
    with threading.Lock():
        window_queue.append(root)

    # 开始事件循环
    root.mainloop()


def check_and_close_windows():
    while True:
        with threading.Lock():
            if len(window_queue) > 5:
                oldest_window = window_queue.popleft()
                oldest_window.after(0, oldest_window.destroy)  # 确保在主线程中销毁窗口
        time.sleep(0.1)  # 每0.1秒检查一次

def generate_windows():
    while True:
        # 在新线程中创建窗口
        threading.Thread(target=create_window).start()
        # 每次生成窗口后等待一段时间
        time.sleep(random.uniform(1, 3))


if __name__ == "__main__":
    # 启动一个线程来检查和关闭窗口
    threading.Thread(target=check_and_close_windows, daemon=True).start()

    # 启动生成窗口的线程
    threading.Thread(target=generate_windows).start()